import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '../stores/user'

const Login = () => import('../views/Login.vue')
const Dashboard = () => import('../views/Dashboard.vue')

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', name: 'Login', component: Login },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: Dashboard,
    meta: { requiresAuth: true },
    children: [
      {
        path: '/techstack',
        name: 'Techstack',
        component: () => import('../views/pages/TechStackManager.vue'),
        meta: { title: '技术栈管理' }
      },
      {
        path: '/product',
        name: 'Product',
        component: () => import('../views/pages/Products/index.vue'),
        meta: { title: '作品管理' }
      },
      {
        path: '/categories',
        name: 'Categories',
        component: () => import('../views/pages/CategoryManager.vue'),
        meta: { title: '项目分类' }
      },
      {
        path: '/platform',
        name: 'Platform',
        component: () => import('../views/pages/PlatformManager.vue'),
        meta: { title: '平台类型维护' }
      },
    ]
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

// 路由拦截
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()

  if (to.meta.requiresAuth) {
    if (userStore.isLoggedIn) {
      next()
    } else {
      next('/login')
    }
  } else {
    // 已登录了，还访问登录页，跳到主页
    if (to.path === '/login' && userStore.isLoggedIn) {
      next('/dashboard')
    } else {
      next()
    }
  }
})


export default router
